//
//  TextViewerView.swift
//  SwiftUIBook
//
//  Created by True on 2023/8/3.
//

import SwiftUI

let NEXT_PAGE_LIMIT: Float = 280

struct TextViewerView: View {
    
    // Simple preference that observes a CGFloat.
    struct ScrollViewOffsetPreferenceKey: PreferenceKey {
        static var defaultValue = CGFloat.zero
        
        static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
            print("v \(value)_ n \(nextValue())")
            value += nextValue()
        }
    }
    
    var textString: String
    
    private var onScrollToEndAction: (()->Void)?
    
    init(textString: String) {
        self.textString = textString
    }
    
    public func onScrollToEnd(_ action: @escaping () -> Void) -> TextViewerView {
        var view = self
        view.onScrollToEndAction = action
        return view
    }
    
    var body: some View {
        GeometryReader { proxyContainer in
            ScrollView {
                ZStack {
                    VStack(alignment: .leading) {
                        Text(textString)
                            .textSelection(.disabled)
                            .font(.title)
                            .foregroundColor(.gray)
                            .lineLimit(nil)
                    }
                    .frame(maxWidth: .infinity, alignment: .leading)
                    
                    GeometryReader { proxy in
                        // let offset = proxy.frame(in: .named("scroll")).minY // 监控页面顶端的Y坐标
                        let offset = proxy.frame(in: .named("scroll")).maxY // 监控页面底端的Y坐标
                        Color.clear.preference(key: ScrollViewOffsetPreferenceKey.self, value: offset)
                    }
                }
            }
            .background()
            .overlay(
                RoundedRectangle(cornerRadius: 5)
                    .stroke(Color.black, lineWidth: 0)
            )
            .colorMultiply(Color(hex: "EAEAEA"))
            .coordinateSpace(name: "scroll")
            .onPreferenceChange(ScrollViewOffsetPreferenceKey.self) { value in
                print("ScrollViewOffsetPreferenceKey ----- \(value)")
                let height = proxyContainer.frame(in: .named("scroll")).height
                print("proxyContainer height  ----- \(height)")
                if Float(value - height) < NEXT_PAGE_LIMIT {
                    //TODO: 需要请求下一页数据了
                    onScrollToEndAction?()
                }
            }
        }
    }
}

struct TextViewerView_Previews: PreviewProvider {
    static var previews: some View {
        TextViewerView(textString: "")
    }
}
